package com.ylcode.libback.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylcode.libback.common.R;
import com.ylcode.libback.model.pojo.Book;
import com.ylcode.libback.model.pojo.Record;
import com.ylcode.libback.service.BookService;
import com.ylcode.libback.service.RecordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/record")
public class RecordController {

    @Resource
    private RecordService recordService;
    @Resource
    private BookService bookService;

    /**
     * 查询记录
     */
    @GetMapping("/findRecordByBookName")
    public R<List<Record>> findRecordByBookName(String param) {
        LambdaQueryWrapper<Record> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Record::getRecordBookName, param);
        List<Record> list = recordService.list(lambdaQueryWrapper);
        return R.success(list);
    }


    /**
     * 借阅信息分页查询
     */
    @GetMapping("/page")
    public R<Page> page (Integer page, Integer pageSize, String name) {
        //创建分页插件
        Page<Record> pageInfo = new Page<>(page, pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Record> recordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        recordLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Record::getRecordBookName, name);
        //添加排序条件
        recordLambdaQueryWrapper.orderByAsc(Record::getRecordBorrowTime);
        //执行查询
        recordService.page(pageInfo, recordLambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 查询书籍总数
     */
    @GetMapping("/total")
    public R<Long> total() {
        long total = recordService.count();
        log.info("总数" + total);
        return R.success(total);
    }

    /**
     * 还书
     * @param recordId
     * @return
     */
    @GetMapping("/retbook/{recordId}")
    public R<String> retbook(@PathVariable String recordId) {
        log.info("事实上");
        long recordIdL = Long.parseLong(recordId);
        Record record = recordService.getById(recordIdL);
        Long bookId = record.getRecordBookId();
        recordService.removeById(record);
        Book book = bookService.getById(bookId);
        book.setBookStatus("0");
        book.setBookBorrower("");
        book.setBookBorrowTime(null);
        book.setBookReturnTime(null);
        bookService.updateById(book);
        return R.success("还书成功");
    }

}
